package com.redis.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * redis 服务类
 */
@Service
public class RedisService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public String getVal(String key) {
        if(key == null || key.trim().equals("")){
            return null;
        }
        Object val = redisTemplate.opsForValue().get(key);
        return Objects.isNull(val) ? null : val.toString();
    }

    public void setVal(String key, String value) {
        if(key == null || key.trim().equals("")){
            return ;
        }
        redisTemplate.opsForValue().set(key,value);
    }

    public void setVal(String key, String value,long expire) {
        if(key == null || key.trim().equals("")){
            return ;
        }
        redisTemplate.opsForValue().set(key,value,expire, TimeUnit.SECONDS);
    }

    public String getHVal(String key,String hashKey){
        if(key == null || key.trim().equals("")){
            return null;
        }
        Object val = redisTemplate.opsForHash().get(key,hashKey);
        return Objects.isNull(val) ? null : val.toString();
    }

    public void setHVal(String key, String hashKey, String value) {
        redisTemplate.opsForHash().put(key,hashKey,value);
    }
}